﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
using System.Windows.Forms;
using Contract;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace client
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public partial class MainForm : Form
    {
       int PCN;
       string Psw;
       ListViewItem lastChosenItem;
      
        public MainForm(int pcn,string password)
        {
            InitializeComponent();

            this.Proxy = createProxy();

            RunCallback(pcn,password);
            MyFile[] mfs = Proxy.Getfilesinfo(pcn.ToString());
            RefreshFileList(mfs);
            refreshGroupList();
           


        }

        public void CreatHost()
        {
            // create a hosting process for Service
            ServiceHost host = new ServiceHost(typeof(CallBack));
            NetTcpBinding binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Buffered;
            binding.ReceiveTimeout = TimeSpan.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            host.AddServiceEndpoint(typeof(ICallBack), binding,
            new Uri("net.tcp://" + Dns.GetHostAddresses(Environment.MachineName)[2].ToString() + ":8001/CallBack"));
          // MessageBox.Show( Dns.GetHostAddresses(Environment.MachineName)[3].ToString());
            host.Open();
            /////////////
        }

        IDataUploader Proxy;


        public void RunCallback(int pcn,string password)
        {
            CreatHost();
            //string pcn =this.PCN.ToString();
            this.PCN = pcn;
            this.Psw = password;
            CallBack.grouphandler = refreshGroupList;
            CallBack.handler = RefreshFileList;
            CallBack.memberhandler = refreshMemberList;
            NewGroup.grouphandler = refreshGroupList;
        }

        public IDataUploader createProxy()
        {
            //////////////////////////////////////
            NetTcpBinding binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Streamed;
            binding.SendTimeout = TimeSpan.MaxValue;
            binding.MaxReceivedMessageSize = 9223372036854775807;
            EndpointAddress address = new EndpointAddress("net.tcp://" + Dns.GetHostAddresses(Environment.MachineName)[2] + ":5000/DataUploader");

            ChannelFactory<IDataUploader> channel = new ChannelFactory<IDataUploader>(binding, address);
            IDataUploader Proxy = channel.CreateChannel();
            return Proxy;
            ///////////////////////////////////////////////
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string PCNlink = PCN.ToString();
            linkLabel1.Text= PCNlink;
            //dynamic 
            tabPage1.Text = @"Private";
            tabPage2.Text = @"Group";

        }

        private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var loc = listView1.HitTest(e.Location);
                if (loc.Item != null)
                {
                    contextMenuStrip1.Show(listView1, e.Location);
                }
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {

            Proxy = createProxy();


            OpenFileDialog dialog = new OpenFileDialog();
            dialog.ShowDialog();
            string filename = Path.GetFileName(dialog.FileName);
            if (dialog.FileName != "")
            {
                Stream uploadStream = new FileStream(dialog.FileName, FileMode.Open);
                string pcn = PCN.ToString();
                MyFile m = new MyFile() { Value = uploadStream, Filename = filename, Size = uploadStream.Length, FileOwnerPCN = pcn };
                try
                {
                    Proxy.Upload(m);
                }
                catch
                {
                    MessageBox.Show("exception");
                }
            }
           
        }




        public void RefreshFileList(MyFile[] files)
        {
            //FileList
            MyFile[] mfs = files;
            mfs = Proxy.Getfilesinfo(PCN.ToString());
            listView1.Items.Clear();
            foreach (var file in mfs)
            {
                ListViewItem item = new ListViewItem(file.FileID);
                item.SubItems.Add( Convert.ToString(file.Filename));
                item.SubItems.Add( Convert.ToString(file.Size));
                item.SubItems.Add( Convert.ToString(file.FileUploadTime));
                listView1.Items.Add(item);
            }

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UserProperty f2 = new UserProperty(PCN.ToString(),this.Psw);
            f2.Show();
        }

        //right click download
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView1.SelectedItems[0];

                MyFile mf = new MyFile();
                mf.Filename = item.SubItems[1].Text;
                //string mf = item.SubItems[1].Text;

                SaveFileDialog dialog = new SaveFileDialog()
                {
                    FileName = Path.GetFileName(mf.Filename)
                };

                dialog.ShowDialog(this);
                if (dialog.FileName != "")
                {
                    using (FileStream output = new FileStream(dialog.FileName, FileMode.Create))
                    {
                        Stream downloadStream = Proxy.Download(mf.Filename,PCN.ToString());
                        byte[] bt = ReadBytestoStream(downloadStream);
                        output.Write(bt, 0, bt.Length);
                        MessageBox.Show("file is downloaded completly!");
                    }

                    Process.Start(dialog.FileName);
                }
                //     ((IClientChannel)Proxy).Close();

            }
        }


        //right click delete
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView1.SelectedItems[0];

               
             //   MyFile[] mfs = Proxy.Getfilesinfo(PCN.ToString());
               // RefreshFileList(mfs);
               
                string name = item.SubItems[1].Text;
                
                Proxy.Delete(name,PCN.ToString());
                
                
            }

        }

        //right click share to..
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView1.SelectedItems[0];




                string fileID = item.SubItems[0].Text;

                Share s = new Share(fileID);
                s.Show();
            }
        }

        public static byte[] ReadBytestoStream(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MyGroup m = new MyGroup() { OwnerPCN = this.PCN.ToString() };
            NewGroup fr = new NewGroup(m,PCN.ToString(),Psw);
            fr.Show();


        //    this.Dispose();
            refreshGroupList();
        }

        public void refreshGroupList()
        {
            //FileList
            MyGroup[] mfs = Proxy.GetGroupInfo(PCN.ToString());
            listView4.Items.Clear();
            foreach (var file in mfs)
            {
                ListViewItem item = new ListViewItem(file.GroupID);
                item.SubItems.Add(Convert.ToString(file.GroupName));
                listView4.Items.Add(item);
            }
        }

        public void refreshMemberList()
        {
            MyUser[] mu = Proxy.GetGroupUser(lastChosenItem.Text.ToString());
            foreach (MyUser u in mu)
            {
                ListViewItem item = new ListViewItem(u.PCN);
              //  item.SubItems.Add(Convert.ToString(file.GroupName));
                listView4.Items.Add(item);
            }
        }

        private void listView4_MouseUp(object sender, MouseEventArgs e)
        {
          
                if (e.Button==MouseButtons.Right)
                {
                    var loc = listView4.HitTest(e.Location);
                    if (loc.Item != null)
                    {
                        contextMenuStrip2.Show(listView4, e.Location);
                    }
                }
            
           
          }

        private void listView4_SelectedIndexChanged(object sender, EventArgs e)
        {
            // listView2.SelectedItems.Clear();
            listView2.Items.Clear();
            listView3.Items.Clear();
            if (listView4.SelectedItems.Count > 0)
            {
                ListView.SelectedListViewItemCollection item = listView4.SelectedItems;
                
                string GroupID = item[0].Text;
                
                MyUser[] mfUsers = Proxy.GetGroupUser(GroupID);
               
                MyFile[] mfFiles = Proxy.GetGroupFiles(GroupID);


                foreach (var User in mfUsers)
                {
                    ListViewItem item2 = new ListViewItem(User.PCN);
                    listView2.Items.Add(item2);
                }

                foreach (var file in mfFiles)
                {
                    ListViewItem item3 = new ListViewItem(file.FileID);
                    listView3.Items.Add(item3);
                }
               // lastChosenItem = listView4.SelectedItems[0];
            }

           


            
        }

        private void addMemberToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView4.SelectedItems.Count ==0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView4.SelectedItems[0];
                string GroupID = item.SubItems[0].Text;
                Addmember am = new Addmember(GroupID);
                am.Show();


            }
            
        }

        private void quitGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView4.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView4.SelectedItems[0];
                string GroupID = item.SubItems[0].Text;
                QuitGroup qg = new QuitGroup(PCN.ToString() ,GroupID);
               // Addmember am = new Addmember(GroupID);
                qg.Show();


            }
        }

        //download GroupFile
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            if (listView3.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView3.SelectedItems[0];

                MyFile mf = new MyFile();
                mf.FileID = item.SubItems[0].Text;
        

                SaveFileDialog dialog = new SaveFileDialog()
                {
                    FileName = Path.GetFileName(mf.Filename)
                };

                dialog.ShowDialog(this);
                if (dialog.FileName != "")
                {
                    using (FileStream output = new FileStream(dialog.FileName, FileMode.Create))
                    {
                        Stream downloadStream = Proxy.Downloadgf(mf.FileID);
                        byte[] bt = ReadBytestoStream(downloadStream);
                        output.Write(bt, 0, bt.Length);
                        MessageBox.Show("file is downloaded completly!");
                    }

                    Process.Start(dialog.FileName);
                }
                //     ((IClientChannel)Proxy).Close();

            }
        }

        //Delete group file
        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            if (listView3.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView3.SelectedItems[0];


                //   MyFile[] mfs = Proxy.Getfilesinfo(PCN.ToString());
                // RefreshFileList(mfs);

                string name = item.SubItems[0].Text;

                Proxy.Delete(name, PCN.ToString());


            }
        }

        private void listView3_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var loc = listView3.HitTest(e.Location);
                if (loc.Item != null)
                {
                    contextMenuStrip3.Show(listView3, e.Location);
                }
            }
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }
     
        }
}

      




